<template>
  <div class="users">
    <div class="users_header">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="users_list_box">
      <div class="users_list_box_box">
        <div class="users_list_box_search">
          <el-input
            placeholder="请输入内容"
            v-model="searchval"
            clearable
            @clear="change"
            class="input-with-select"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="search"
            ></el-button>
          </el-input>
          <el-button type="primary" class="add_user" @click="adduser"
            >添加用户</el-button
          >
          <!-- 添加用户 -->
          <el-dialog
            title="添加用户"
            :visible.sync="dialogVisible"
            width="50%"
            destroy-on-close
          >
            <div>
              <el-form
                label-position="left"
                label-width="80px"
                :model="ruleForm"
                status-icon
                :rules="rules"
                ref="ruleForm"
              >
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="ruleForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input v-model="ruleForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="ruleForm.email"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                  <el-input v-model="ruleForm.mobile"></el-input>
                </el-form-item>
              </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="resetForm('ruleForm')">取 消</el-button>
              <el-button type="primary" @click="submitForm('ruleForm')"
                >确 定</el-button
              >
            </span>
          </el-dialog>
        </div>
        <div class="user_list_box_body">
          <el-table :data="usersdata" border style="width: 100%">
            <el-table-column prop="order" label="#" width="100">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="username" label="姓名" width="197">
            </el-table-column>
            <el-table-column prop="email" label="邮箱" width="197">
            </el-table-column>
            <el-table-column prop="mobile" label="电话" width="197">
            </el-table-column>
            <el-table-column prop="role_name" label="角色" width="197">
            </el-table-column>
            <el-table-column prop="mg_state" label="状态" width="197">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.mg_state"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                  @change="changestatus(scope.row)"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="handle" label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="alteruser(scope.row)"
                ></el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="open(scope.row)"
                ></el-button>
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  @click="getdscope(scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentpage"
            :page-sizes="[1, 2, 3, 4]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
        <!-- 修改编辑用户 -->
        <el-dialog title="编辑用户" :visible.sync="dialogFormuser">
          <el-form
            label-position="left"
            label-width="80px"
            :model="formAlter"
            ref="formAlter"
          >
            <el-form-item label="用户名">
              <el-input disabled v-model="formAlter.username"></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="formAlter.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="formAlter.mobile"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormuser = false">取 消</el-button>
            <el-button type="primary" @click="alterchange('formAlter')"
              >确 定</el-button
            >
          </div>
        </el-dialog>

        <!-- 分配角色的框 -->
        <el-dialog title="分配角色" :visible.sync="dialogRlose">
          <el-form label-position="left">
            <el-form-item label="当前用户" label-width="120px">
              {{ form.username }}
            </el-form-item>
            <el-form-item label="当前角色" label-width="120px">
              {{ form.role_name }}
            </el-form-item>

            <el-form-item label="分配新角色" label-width="120px">
              <el-select v-model="form.rid" placeholder="请选择">
                <el-option
                  :label="item.roleName"
                  :value="item.id"
                  v-for="item in form.ridarr"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogRlose = false">取 消</el-button>
            <el-button type="primary" @click="suregetdscope">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getUsers,
  setUsers,
  setUsersstatus,
  setUsersalter,
  setdeleteUser,
  getRoles,
  setRoles,
} from "@/api/http.js";
export default {
  data() {
    // 用户名的判断
    var validateUser = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        let arg = /^[a-zA-Z0-9]{3,10}$/;
        if (!arg.test(value)) {
          callback(new Error("字符长度在 3 到 10 个字符"));
        } else {
          callback();
        }
      }
    };
    //密码的判断
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        let arg = /^[a-zA-Z0-9]{6,15}$/;
        if (!arg.test(value)) {
          callback(new Error("字符长度在 6 到 15 个字符"));
        } else {
          callback();
        }
      }
    };
    //邮箱判断
    var validateEmail = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入邮箱"));
      } else {
        let arg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
        if (!arg.test(value)) {
          callback(new Error("邮箱格式错误"));
        } else {
          callback();
        }
      }
    };
    //电话判断
    var validateMobile = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入电话号码"));
      } else {
        let arg =
          /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/;
        if (!arg.test(value)) {
          callback(new Error("手机号错误"));
        } else {
          callback();
        }
      }
    };

    return {
      usersdata: [], // 用户数据
      total: 0, //总用户数,
      currentpage: 1, // 当前页,
      pagesize: 3, // 每页几条数据
      searchval: "", //搜索内容
      dialogVisible: false, // 添加用户 弹框 是否开启
      dialogFormuser: false, // 修改 用户 弹框 是否开启
      dialogRlose: false, // 角色分配 弹框 是否开启
      form: {
        id: "",
        rid: "",
        username: "",
        role_name: "",
        ridarr: [],
      },
      ruleForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      rules: {
        username: [{ validator: validateUser, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
        email: [{ validator: validateEmail, trigger: "blur" }],
        mobile: [{ validator: validateMobile, trigger: "blur" }],
      },
      formAlter: {
        username: "",
        email: "",
        mobile: "",
      },
    };
  },
  mounted() {
    // 用户数据
    this.getUsersdata();
  },
  methods: {
    // 用户数据
    getUsersdata() {
      getUsers({
        data: {
          query: this.searchval,
          pagenum: this.currentpage,
          pagesize: this.pagesize,
        },
      }).then((res) => {
        this.usersdata = res.data.users;

        this.total = res.data.total;
        console.log(res);
      });
    },
    handleCurrentChange(val) {
      // 当前页
      this.currentpage = val;
      // console.log(114, this.currentpage);
      this.getUsersdata();
    },
    handleSizeChange(val) {
      //每页条数发生改变
      console.log(121, val);
      this.pagesize = val;
      this.getUsersdata();
    },
    // 点击搜索
    search() {
      this.getUsersdata();
    },
    // 清空时 自动触发
    change() {
      this.getUsersdata();
    },
    adduser() {
      this.dialogVisible = true;
      this.ruleForm = {
        username: "",
        password: "",
        email: "",
        mobile: "",
      };
    },
    //取消 重置添加用户
    resetForm(ruleForm) {
      this.$refs[ruleForm].resetFields();
      this.dialogVisible = false;
    },
    // 提交 添加用户
    submitForm(ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          console.log(this.ruleForm);
          let usersjion = this.ruleForm;
          this.setUsersdata(usersjion);

          this.dialogVisible = false;
        } else {
          this.$message({
            message: "error submit!!",
            type: "warning",
          });
          return false;
        }
      });
    },
    // 提交数据 接口
    setUsersdata(usersjion) {
      setUsers({
        data: {
          username: usersjion.username,
          password: usersjion.password,
          email: usersjion.email,
          mobile: usersjion.mobile,
        },
      }).then((res) => {
        this.getUsersdata();
        // console.log(res);
      });
    },
    // 修改用户状态
    changestatus(scope) {
      let type = scope.mg_state;
      let uld = scope.id;
      console.log(scope);
      setUsersstatus({
        type: type,
        uld: uld,
      }).then((res) => {
        console.log(res);
        this.$message({
          message: res.meta.msg,
          duration: 1000,
          type: "success",
        });
      });
    },
    //修改用户的信息
    alteruser(scope) {
      console.log(scope);
      this.formAlter = {
        username: scope.username,
        email: scope.email,
        mobile: scope.mobile,
        id: scope.id,
      };
      this.dialogFormuser = true;
    },
    // 提交修改
    alterchange(formAlter) {
      this.$refs[formAlter].validate((valid) => {
        if (valid) {
          console.log(this.formAlter);
          let alterjson = {
            email: this.formAlter.email,
            mobile: this.formAlter.mobile,
            id: this.formAlter.id,
          };
          this.setUsersalterdata(alterjson);
          this.dialogFormuser = false;
        } else {
          return false;
        }
      });
    },
    //修改数据 提交接口
    setUsersalterdata(alterjson) {
      setUsersalter({
        id: alterjson.id,
        data: {
          email: alterjson.email,
          mobile: alterjson.mobile,
        },
      }).then((res) => {
        console.log(res);
        this.getUsersdata();
        this.$message({
          message: res.meta.msg,
          duration: 1000,
          type: "success",
        });
      });
    },
    // 删除单个用户 数据
    open(scope) {
      let id = scope.id;
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.setdeleteUserdata(id);

          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 删除调接口
    setdeleteUserdata(cid) {
      setdeleteUser({
        id: cid,
      })
        .then((res) => {
          this.getUsersdata();
        })
        .catch((err) => {
          // console.log(err);
        });
    },
    //分配角色
    getdscope(scope) {
      this.dialogRlose = true;
      this.form.username = scope.username;
      this.form.role_name = scope.role_name;
      this.form.id = scope.id;
      console.log(452, scope);
      // let id  = scope.id
      getRoles().then((res) => {
        console.log(res.data);
        this.form.ridarr = res.data;
      });
      // console.log(scope);
    },
    // 确定 分配 橘色
    suregetdscope() {
      this.dialogRlose = false;
      let parems = {
        id: this.form.id,
        rid: this.form.rid,
      };
      // console.log(parems);
      // console.log(this.form.rid);
      // console.log(this.form.id);
      setRoles(parems)
        .then((res) => {
          this.getUsersdata();
          // console.log(467, res);
          this.$message({
            message: res.meta.msg,
            type: "success",
          });
        })
        .catch((err) => {});
    },
  },
  components: {},
};
</script>

<style lang='scss'>
.users {
  width: 100%;
  height: 100%;
  background: #eee;
  .users_header {
    width: 100%;
    height: 80px;
    // line-height: 80px;
    padding-top: 30px;
    padding-left: 40px;
  }
  .users_list_box {
    width: 100%;
    height: calc(100% - 80px);
    .users_list_box_box {
      width: 95%;
      height: 100%;
      background: #fff;
      margin: 0 auto;
      .users_list_box_search {
        width: 95%;
        height: 80px;
        margin: 0 auto;
        line-height: 80px;
        .input-with-select {
          width: 400px;
        }
        .add_user {
          margin-left: 20px;
        }
      }
      .user_list_box_body {
        width: 95%;
        height: calc(100% - 80px);
        margin: 0 auto;
      }
    }
  }
}
</style>
